package com.yuncheng.oaApi.weboffice;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yuncheng.oaApi.utils.GetUuIdUtils;;
import com.yuncheng.oaApi.config.OaMinioUtils;
import com.yuncheng.oaApi.constant.OaBusinessConstant;
import com.yuncheng.oaApi.constant.OaCommonFlowConstant;
import com.yuncheng.oaApi.entity.OaFjzykEntity;
import com.yuncheng.oaApi.entity.OaWjjl;
import com.yuncheng.exception.BusinessException;
import com.yuncheng.oaApi.service.IOaWjjlService;
import com.yuncheng.spcyApi.constant.webOffice.WebOfficeConstant;
import com.yuncheng.spcyApi.utils.CharacterEncodingConvertUtils;
import com.yuncheng.oaApi.utils.OaLocalFileUploadUtils;
import com.yuncheng.oaApi.vo.Result;
import com.yuncheng.spcyApi.utils.StringPatternUtils;
import com.yuncheng.utils.ThreadContextHelper;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import utils.LogUtils;
import utils.ObjectToMapUtils;
import utils.Util;

import javax.annotation.Resource;
import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Component
public class OaWebOfficeFile {
    private static final Logger log = LoggerFactory.getLogger(OaWebOfficeFile.class);

    @Resource
    private OaBusinessConstant oaBusinessConstant;

    @Resource
    @Lazy
    private OaLocalFileUploadUtils oaLocalFileUploadUtils;


    @Resource
    private IOaWjjlService oaWjjlService;

    @Resource
    @Lazy
    private OaMinioUtils oaMinioUtils;

    @Resource
    private WebOfficeConstant webOfficeConstant;

    /**
     * 上传文件到WebOffice服务器
     * @param fileName 上传文件名带后缀
     * @param saveUrl 上传的文件相对路径
     * @return
     */
    public Result uploadWebOfficeFile(OaWjjl wjjl, String fileName, String saveUrl) {
        if (StringUtils.isBlank(saveUrl)) {
            return Result.error("存储路径为空,请重新生成文件");
        }
        if (StringUtils.isBlank(wjjl.getFwjlx())) {
            return Result.error("文件类型为空,请重新生成文件");
        }
        if (wjjl.getFwjlx().equals(".pdf")) {
            return Result.error("pdf文件无法上传");
        }
        File file = new File(oaBusinessConstant.UPLOAD_FILE_OAFJ + saveUrl);
        if (!file.exists()) {
            return Result.error("本地文件不存在");
        }

        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            log.error("上传WebOffice文件失败，获取文件流出错，文件不存在: {}", e.getMessage());
            return Result.error("上传WebOffice文件失败，获取文件流出错，文件不存在");
        }

        if (StringUtils.isEmpty(fileName)) {
            return Result.error("上传WebOffice文件失败，缺少参数文件fileName");
        }

        if (StringUtils.isEmpty(saveUrl)) {
            return Result.error("上传WebOffice文件失败，缺少保存的路径");
        }

        String url = webOfficeConstant.WebOffice_Upload_File_Api;
        HttpPost httpRequest = new HttpPost(url);

        try {
            // json参数
//            MultipartFile file = siteMaterialsVo.getFile();
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            multipartEntityBuilder.setMode(HttpMultipartMode.RFC6532);   // 处理中文文件名称乱码
            multipartEntityBuilder.setCharset(Charset.forName("UTF-8"));
            multipartEntityBuilder.addBinaryBody("file", fileInputStream, ContentType.MULTIPART_FORM_DATA, fileName);
            multipartEntityBuilder.addTextBody("filePath", saveUrl);
            HttpEntity httpEntity = multipartEntityBuilder.build();
            httpRequest.setEntity(httpEntity);

            HttpResponse response = HttpClients.createDefault().execute(httpRequest);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity res = response.getEntity();
                if (res != null) {
                    String s = EntityUtils.toString(res, "UTF-8");
                    JSONObject jsonObject = JSONObject.parseObject(s);
                    String errorCode = jsonObject.getString("errorCode");
                    log.info("errorcode: {}", errorCode);
                    String errorMessage = jsonObject.getString("errorMessage");
                    log.info("errorMessage: {}", errorMessage);
                    if (errorCode.equals("0")) {
                        /*String fcflj = wjjl.getFcflj();
                        wjjl.setFjdcflj(fcflj);
                        spcySqsxWjjlService.updateById(wjjl);*/

                        return Result.ok("上传成功");
                    } else {
                        log.error("上传WebOffice文件失败: {}", errorMessage);
                        return Result.error("上传WebOffice文件失败: " + errorMessage);
                    }
                }
            } else {
                log.error("上传WebOffice文件失败，状态码不是200");
                return Result.error("上传WebOffice文件失败，状态码不是200");
            }
        } catch (Exception e) {
            log.error("上传WebOffice文件失败：{}", e.getMessage());
            return Result.error("上传WebOffice文件失败: " + e.getMessage());
        }

        return Result.ok("上传成功");
    }

    /**
     * 上传文件到WebOffice服务器  (质量体系文件)
     *
     * @param fileName 上传文件名带后缀
     * @param saveUrl  上传的文件相对路径
     * @return
     */
    public Result uploadWebOfficeFileByZltxwj(OaWjjl wjjl, String fileName, String saveUrl) {
        if (StringUtils.isBlank(saveUrl)) {
            return Result.error("存储路径为空,请重新生成文件");
        }
        if (StringUtils.isBlank(wjjl.getFwjlx())) {
            return Result.error("文件类型为空,请重新生成文件");
        }
        if (wjjl.getFwjlx().equals(".pdf")) {
            return Result.error("pdf文件无法上传");
        }
        File file = new File(oaBusinessConstant.UPLOAD_FILE_ROOT + saveUrl);
        if (!file.exists()) {
            return Result.error("本地文件不存在");
        }

        fileName = CharacterEncodingConvertUtils.chineseToUnicode(fileName);
        saveUrl = CharacterEncodingConvertUtils.chineseToUnicode(saveUrl);

        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            log.error("上传WebOffice文件失败，获取文件流出错，文件不存在: {}", e.getMessage());
            return Result.error("上传WebOffice文件失败，获取文件流出错，文件不存在");
        }

        if (StringUtils.isEmpty(fileName)) {
            return Result.error("上传WebOffice文件失败，缺少参数文件fileName");
        }

        if (StringUtils.isEmpty(saveUrl)){
            return Result.error("上传WebOffice文件失败，缺少保存的路径");
        }

        String url = webOfficeConstant.WebOffice_Upload_File_Api;
        HttpPost httpRequest = new HttpPost(url);

        try {
            // json参数
//            MultipartFile file = siteMaterialsVo.getFile();
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            multipartEntityBuilder.setMode(HttpMultipartMode.RFC6532);   // 处理中文文件名称乱码
            multipartEntityBuilder.setCharset(Charset.forName("UTF-8"));
            multipartEntityBuilder.addBinaryBody("file", fileInputStream, ContentType.MULTIPART_FORM_DATA, fileName);
            multipartEntityBuilder.addTextBody("filePath", saveUrl);
            HttpEntity httpEntity = multipartEntityBuilder.build();
            httpRequest.setEntity(httpEntity);

            HttpResponse response = HttpClients.createDefault().execute(httpRequest);
            if (response.getStatusLine().getStatusCode() == 200){
                HttpEntity res = response.getEntity();
                if (res != null) {
                    String s = EntityUtils.toString(res, "UTF-8");
                    JSONObject jsonObject = JSONObject.parseObject(s);
                    String errorCode = jsonObject.getString("errorCode");
                    log.info("errorcode: {}",errorCode);
                    String errorMessage = jsonObject.getString("errorMessage");
                    log.info("errorMessage: {}",errorMessage);
                    if (errorCode.equals("0")){
                        /*String fcflj = wjjl.getFcflj();
                        wjjl.setFjdcflj(fcflj);
                        spcySqsxWjjlService.updateById(wjjl);*/

                        return Result.ok("上传成功");
                    } else {
                        log.error("上传WebOffice文件失败: {}",errorMessage);
                        return Result.error("上传WebOffice文件失败: "+errorMessage);
                    }
                }
            }else {
                log.error("上传WebOffice文件失败，状态码不是200");
                return Result.error("上传WebOffice文件失败，状态码不是200");
            }
        } catch (Exception e) {
            log.error("上传WebOffice文件失败：{}", e.getMessage());
            return Result.error("上传WebOffice文件失败: " + e.getMessage());
        }

        return Result.ok("上传成功");
    }

    /**
     * 上传文件到WebOffice服务器 （文件模板库）
     *
     * @param fileName 上传文件名带后缀
     * @param saveUrl  上传的文件相对路径
     * @return
     */
    public Result uploadWebOfficeFileByOafj(OaFjzykEntity wjjl, String fileName, String saveUrl) throws IOException {
        if (StringUtils.isBlank(saveUrl)) {
            return Result.error("存储路径为空,请重新生成文件");
        }
        if (StringUtils.isBlank(wjjl.getFwjlx())) {
            return Result.error("文件类型为空,请重新生成文件");
        }
        if (wjjl.getFwjlx().equals(".pdf")) {
            return Result.error("pdf文件无法上传");
        }
//        File file = new File(businessConstant.UPLOAD_FILE_OAFJ + saveUrl);
////        if (!file.exists()) {
////            return Result.error("本地文件不存在");
////        }
        boolean isMinio = true;
        InputStream minioInput = oaMinioUtils.getObject(saveUrl);
        File file = this.asFile(minioInput, Util.getWjHz(fileName), oaBusinessConstant.TEMPORARY_UPLOAD_MKDIR_ROOT + "/temp", "TEP");


//        fileName = "xxx.doc";
        fileName = CharacterEncodingConvertUtils.chineseToUnicode(fileName);
//        System.out.println("2Name: "+fileName);
//        saveUrl = "/xxx.doc";
        saveUrl = CharacterEncodingConvertUtils.chineseToUnicode(saveUrl);
//        System.out.println("2: "+saveUrl);

        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            log.error("上传WebOffice文件失败，获取文件流出错，文件不存在: {}", e.getMessage());
            return Result.error("上传WebOffice文件失败，获取文件流出错，文件不存在");
        }
        if (isMinio) {
            file.delete();
        }

        if (StringUtils.isEmpty(fileName)) {
            return Result.error("上传WebOffice文件失败，缺少参数文件fileName");
        }

        if (StringUtils.isEmpty(saveUrl)) {
            return Result.error("上传WebOffice文件失败，缺少保存的路径");
        }

        String url = webOfficeConstant.WebOffice_Upload_File_Api;
        HttpPost httpRequest = new HttpPost(url);

        try {
            // json参数
//            MultipartFile file = siteMaterialsVo.getFile();
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            multipartEntityBuilder.setMode(HttpMultipartMode.RFC6532);   // 处理中文文件名称乱码
//            multipartEntityBuilder.setMode(HttpMultipartMode.STRICT);   // 处理中文文件名称乱码
            multipartEntityBuilder.setCharset(Charset.forName("UTF-8"));
            multipartEntityBuilder.addBinaryBody("file", fileInputStream, ContentType.MULTIPART_FORM_DATA, fileName);
            multipartEntityBuilder.addTextBody("filePath", saveUrl);
            HttpEntity httpEntity = multipartEntityBuilder.build();
            httpRequest.setEntity(httpEntity);

            HttpResponse response = HttpClients.createDefault().execute(httpRequest);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity res = response.getEntity();
                if (res != null) {
                    String s = EntityUtils.toString(res, "UTF-8");
                    JSONObject jsonObject = JSONObject.parseObject(s);
                    String errorCode = jsonObject.getString("errorCode");
                    log.info("errorcode: {}", errorCode);
                    String errorMessage = jsonObject.getString("errorMessage");
                    log.info("errorMessage: {}", errorMessage);
                    if (errorCode.equals("0")) {
                        /*String fcflj = wjjl.getFcflj();
                        wjjl.setFjdcflj(fcflj);
                        spcySqsxWjjlService.updateById(wjjl);*/

                        return Result.ok("上传成功");
                    } else {
                        log.error("上传WebOffice文件失败: {}", errorMessage);
                        return Result.error("上传WebOffice文件失败: " + errorMessage);
                    }
                }
            } else {
                log.error("上传WebOffice文件失败，状态码不是200");
                return Result.error("上传WebOffice文件失败，状态码不是200");
            }
        } catch (Exception e) {
            log.error("上传WebOffice文件失败：{}", e.getMessage());
            return Result.error("上传WebOffice文件失败: " + e.getMessage());
        }

        return Result.ok("上传成功");
    }

    //创建临时文件
    public static FileInputStream convertToFileInputStream(InputStream inputStream, String fileName) throws IOException {
        File tempFile = File.createTempFile("temp", Util.getWjHz(fileName));
        tempFile.deleteOnExit();

        try (FileOutputStream outputStream = new FileOutputStream(tempFile)) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }

        return new FileInputStream(tempFile);
    }

    public static File asFile(InputStream inputStream, String wjhz, String url, String fileName) throws IOException {
//        System.out.println(wjhz);
//        System.out.println(url);
//        System.out.println(fileName);
        File tmp = File.createTempFile(fileName, wjhz, new File(url));
        OutputStream os = new FileOutputStream(tmp);
        int bytesRead = 0;
        byte[] buffer = new byte[8192];
        while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        inputStream.close();
        return tmp;
    }


    public Result uploadWebOfficeFileByOazw(OaWjjl wjjl, String fileName, String saveUrl) {
        if (StringUtils.isBlank(saveUrl)) {
            return Result.error("存储路径为空,请重新生成文件");
        }
        if (StringUtils.isBlank(wjjl.getFwjlx())) {
            return Result.error("文件类型为空,请重新生成文件");
        }
        if (wjjl.getFwjlx().equals(".pdf")) {
            return Result.error("pdf文件无法上传");
        }
        File file = new File(oaBusinessConstant.UPLOAD_OA_ZW + saveUrl);
        if (!file.exists()) {
            return Result.error("本地文件不存在");
        }

//        fileName = "xxx.doc";
        fileName = CharacterEncodingConvertUtils.chineseToUnicode(fileName);
//        System.out.println("2Name: "+fileName);
//        saveUrl = "/xxx.doc";
        saveUrl = CharacterEncodingConvertUtils.chineseToUnicode(saveUrl);
//        System.out.println("2: "+saveUrl);

        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            log.error("上传WebOffice文件失败，获取文件流出错，文件不存在: {}", e.getMessage());
            return Result.error("上传WebOffice文件失败，获取文件流出错，文件不存在");
        }

        if (StringUtils.isEmpty(fileName)) {
            return Result.error("上传WebOffice文件失败，缺少参数文件fileName");
        }

        if (StringUtils.isEmpty(saveUrl)) {
            return Result.error("上传WebOffice文件失败，缺少保存的路径");
        }

        String url = webOfficeConstant.WebOffice_Upload_File_Api;
        HttpPost httpRequest = new HttpPost(url);

        try {
            // json参数
//            MultipartFile file = siteMaterialsVo.getFile();
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            multipartEntityBuilder.setMode(HttpMultipartMode.RFC6532);   // 处理中文文件名称乱码
//            multipartEntityBuilder.setMode(HttpMultipartMode.STRICT);   // 处理中文文件名称乱码
            multipartEntityBuilder.setCharset(Charset.forName("UTF-8"));
            multipartEntityBuilder.addBinaryBody("file", fileInputStream, ContentType.MULTIPART_FORM_DATA, fileName);
            multipartEntityBuilder.addTextBody("filePath", saveUrl);
            HttpEntity httpEntity = multipartEntityBuilder.build();
            httpRequest.setEntity(httpEntity);

            HttpResponse response = HttpClients.createDefault().execute(httpRequest);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity res = response.getEntity();
                if (res != null) {
                    String s = EntityUtils.toString(res, "UTF-8");
                    JSONObject jsonObject = JSONObject.parseObject(s);
                    String errorCode = jsonObject.getString("errorCode");
                    log.info("errorcode: {}", errorCode);
                    String errorMessage = jsonObject.getString("errorMessage");
                    log.info("errorMessage: {}", errorMessage);
                    if (errorCode.equals("0")) {
                        /*String fcflj = wjjl.getFcflj();
                        wjjl.setFjdcflj(fcflj);
                        spcySqsxWjjlService.updateById(wjjl);*/

                        return Result.ok("上传成功");
                    } else {
                        log.error("上传WebOffice文件失败: {}", errorMessage);
                        return Result.error("上传WebOffice文件失败: " + errorMessage);
                    }
                }
            } else {
                log.error("上传WebOffice文件失败，状态码不是200");
                return Result.error("上传WebOffice文件失败，状态码不是200");
            }
        } catch (Exception e) {
            log.error("上传WebOffice文件失败：{}", e.getMessage());
            return Result.error("上传WebOffice文件失败: " + e.getMessage());
        }

        return Result.ok("上传成功");
    }


    //打开文档（只读）
    public String openFileByOafj(OaFjzykEntity wjjl, String fileId, String saveUrl, int count) {
//        saveUrl = "/xxx.doc";
        saveUrl = CharacterEncodingConvertUtils.chineseToUnicode(saveUrl);
        saveUrl = CharacterEncodingConvertUtils.replaceSpecialString(saveUrl);
        log.info("1: {}", saveUrl);
        String params = "";
        params += "{";
        params += "\"method\": " + 1 + ",";
        params += "\"params\":";
        params += "{";
        params += "\"userRight\": " + 1 + ",";
//        params += "\"userId\": \"" + WebOfficeConstant.WebOffice_User_Id + "\",";
        params += "\"userId\": \"" + ThreadContextHelper.getCurrentUser().getName() +"("+ThreadContextHelper.getCurrentUser().getOrgName()+")" + "\",";

        params += "\"fileId\": \"" + fileId + "\",";
        params += "\"filePath\": \"" + saveUrl + "\"";
        params += "}";
        params += "}";
        JSONObject jsonParams = JSON.parseObject(params);

        // 转码参数 utf-8
        String paramsDecode = "";
        paramsDecode = StringPatternUtils.encode(jsonParams.toString());

        StringBuffer reqHttpUrl = new StringBuffer(webOfficeConstant.WebOffice_Api);
        reqHttpUrl.append("?");
        reqHttpUrl.append("jsonParams").append("=").append(paramsDecode);
        HttpPost httpRequest = initHttpPost(reqHttpUrl.toString());
//        httpRequest.setEntity(new StringEntity(jsonParams.toString(),"UTF-8"));
        try {
            HttpResponse response = HttpClients.createDefault().execute(httpRequest);

            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity res = response.getEntity();
                if (res != null) {
                    String s = EntityUtils.toString(res, "UTF-8");

                    JSONObject jsonObject2 = JSONObject.parseObject(s);

                    String errorCode = jsonObject2.getString("errorCode");
                    log.info("打开文档-errorCode: {}", errorCode);


                    String errorMessage = jsonObject2.getString("errorMessage");
                    log.info("打开文档-errorMessage: {}", errorMessage);
                    if (errorCode.equals("0")) {
                        log.info("打开文档-errorMessage: {}", errorMessage);
                        JSONObject result = jsonObject2.getJSONObject("result");
                        String urls = result.getString("urls");
                        return urls;
                    } else if (errorCode.equals("400001")) {
                        if (errorMessage.equals("文档不存在。")) {
                            if (count == 0) {
                                return "";
                            }
                            Result result = this.uploadWebOfficeFileByOafj(wjjl, wjjl.getFwjmc(), wjjl.getFwjlj());
                            if (!result.isSuccess()) {
                                log.error("将WebOffice服务器中的word文件下载的文档不存在，上传文档失败：{}", result.getMessage());
                                throw new BusinessException("将WebOffice服务器中的word文件下载的文档不存在，上传文档失败：{}" + result.getMessage());
                            } else {
                                if (count == 0) {
                                    return "";
                                }
                                count = count - 1;
                                String url2 = this.openFileByOafj(wjjl, fileId, saveUrl, count);
                                return url2;
                            }
                        } else {
                            log.error("打开文档-errorMessage: {}", errorMessage);
                            throw new BusinessException("打开文档-errorMessage: {}" + errorMessage);
                        }
                    }
                }
            } else {
                log.error("关闭文档response-code: {}", response.getStatusLine().getStatusCode());
                throw new BusinessException("参数转码失败：" + response.getStatusLine().getStatusCode());
            }
        } catch (Exception e) {
            log.error("判断文档文件是否被打开出错Exception：{}", e.getMessage());
            throw new BusinessException("参数转码失败：" + e.getMessage());
        }

        return "";
    }



    public String openFileByOafjbj(OaFjzykEntity wjjl, String fileId, String saveUrl, int count) {
//        saveUrl = "/xxx.doc";
        saveUrl = CharacterEncodingConvertUtils.chineseToUnicode(saveUrl);
        saveUrl = CharacterEncodingConvertUtils.replaceSpecialString(saveUrl);
        log.info("1: {}", saveUrl);
        String params = "";
        params += "{";
        params += "\"method\": " + 1 + ",";
        params += "\"params\":";
        params += "{";
        params += "\"userRight\": " + 0 + ",";//可编辑
//        params += "\"userId\": \"" + WebOfficeConstant.WebOffice_User_Id + "\",";
        params += "\"userId\": \"" + ThreadContextHelper.getCurrentUser().getName() +"("+ThreadContextHelper.getCurrentUser().getOrgName()+")" + "\",";

        params += "\"fileId\": \"" + fileId + "\",";
        params += "\"filePath\": \"" + saveUrl + "\"";
        params += "}";
        params += "}";
        JSONObject jsonParams = JSON.parseObject(params);

        // 转码参数 utf-8
        String paramsDecode = "";
        paramsDecode = StringPatternUtils.encode(jsonParams.toString());

        StringBuffer reqHttpUrl = new StringBuffer(webOfficeConstant.WebOffice_Api);
        reqHttpUrl.append("?");
        reqHttpUrl.append("jsonParams").append("=").append(paramsDecode);
        HttpPost httpRequest = initHttpPost(reqHttpUrl.toString());
//        httpRequest.setEntity(new StringEntity(jsonParams.toString(),"UTF-8"));
        try {
            HttpResponse response = HttpClients.createDefault().execute(httpRequest);

            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity res = response.getEntity();
                if (res != null) {
                    String s = EntityUtils.toString(res, "UTF-8");

                    JSONObject jsonObject2 = JSONObject.parseObject(s);

                    String errorCode = jsonObject2.getString("errorCode");
                    log.info("打开文档-errorCode: {}", errorCode);

                    String errorMessage = jsonObject2.getString("errorMessage");
                    if (errorCode.equals("0")) {
                        log.info("打开文档-errorMessage: {}", errorMessage);
                        JSONObject result = jsonObject2.getJSONObject("result");
                        String urls = result.getString("urls");
                        return urls;
                    } else if (errorCode.equals("400001")) {
                        if (errorMessage.equals("文档不存在。")) {
                            if (count == 0) {
                                return "";
                            }
                            Result result = this.uploadWebOfficeFileByOafj(wjjl, wjjl.getFwjmc(), wjjl.getFwjlj());
                            if (!result.isSuccess()) {
                                log.error("将WebOffice服务器中的word文件下载的文档不存在，上传文档失败：{}", result.getMessage());
                                throw new BusinessException("将WebOffice服务器中的word文件下载的文档不存在，上传文档失败：{}" + result.getMessage());
                            } else {
                                if (count == 0) {
                                    return "";
                                }
                                count = count - 1;
                                String url2 = this.openFileByOafj(wjjl, fileId, saveUrl, count);
                                return url2;
                            }
                        } else {
                            log.error("打开文档-errorMessage: {}", errorMessage);
                            throw new BusinessException("打开文档-errorMessage: {}" + errorMessage);
                        }
                    }

                }
            } else {
                log.error("关闭文档response-code: {}", response.getStatusLine().getStatusCode());
                throw new BusinessException("参数转码失败：" + response.getStatusLine().getStatusCode());
            }
        } catch (Exception e) {
            log.error("判断文档文件是否被打开出错Exception：{}", e.getMessage());
            throw new BusinessException("参数转码失败：" + e.getMessage());
        }

        return "";
    }


    //打开文档（编辑） 正文
    public String openFileByOazw(OaWjjl wjjl, String fileId, String saveUrl, int count) {
//        saveUrl = "/xxx.doc";
        saveUrl = CharacterEncodingConvertUtils.chineseToUnicode(saveUrl);
        saveUrl = CharacterEncodingConvertUtils.replaceSpecialString(saveUrl);
        log.info("1: {}", saveUrl);
        String params = "";
        params += "{";
        params += "\"method\": " + 1 + ",";
        params += "\"params\":";
        params += "{";
        params += "\"userRight\": " + 0 + ",";//可编辑
//        params += "\"userId\": \"" + WebOfficeConstant.WebOffice_User_Id + "\",";
        params += "\"userId\": \"" + ThreadContextHelper.getCurrentUser().getName() +"("+ThreadContextHelper.getCurrentUser().getOrgName()+")" + "\",";

        params += "\"fileId\": \"" + fileId + "\",";
        params += "\"filePath\": \"" + saveUrl + "\"";
        params += "}";
        params += "}";
        JSONObject jsonParams = JSON.parseObject(params);

        // 转码参数 utf-8
        String paramsDecode = "";
        paramsDecode = StringPatternUtils.encode(jsonParams.toString());

        StringBuffer reqHttpUrl = new StringBuffer(webOfficeConstant.WebOffice_Api);
        reqHttpUrl.append("?");
        reqHttpUrl.append("jsonParams").append("=").append(paramsDecode);
        HttpPost httpRequest = initHttpPost(reqHttpUrl.toString());
//        httpRequest.setEntity(new StringEntity(jsonParams.toString(),"UTF-8"));
        try {
            HttpResponse response = HttpClients.createDefault().execute(httpRequest);

            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity res = response.getEntity();
                if (res != null) {
                    String s = EntityUtils.toString(res, "UTF-8");

                    JSONObject jsonObject2 = JSONObject.parseObject(s);

                    String errorCode = jsonObject2.getString("errorCode");
                    log.info("打开文档-errorCode: {}", errorCode);

                    String errorMessage = jsonObject2.getString("errorMessage");
                    if (errorCode.equals("0")) {
                        log.info("打开文档-errorMessage: {}", errorMessage);
                        JSONObject result = jsonObject2.getJSONObject("result");
                        String urls = result.getString("urls");
                        return urls;
                    } else if (errorCode.equals("400001")) {
                        if (errorMessage.equals("文档不存在。")) {
                            if (count == 0) {
                                return "";
                            }
                            Result result = this.uploadWebOfficeFileByOazw(wjjl, wjjl.getFwjccmc(), wjjl.getFjdcflj());
                            if (!result.isSuccess()) {
                                log.error("将WebOffice服务器中的word文件下载的文档不存在，上传文档失败：{}", result.getMessage());
                                throw new BusinessException("将WebOffice服务器中的word文件下载的文档不存在，上传文档失败：{}" + result.getMessage());
                            } else {
                                if (count == 0) {
                                    return "";
                                }
                                count = count - 1;
                                String url2 = this.openFileByOazw(wjjl, fileId, saveUrl, count);
                                return url2;
                            }
                        } else {
                            log.error("打开文档-errorMessage: {}", errorMessage);
                            throw new BusinessException("打开文档-errorMessage: {}" + errorMessage);
                        }
                    }

                }
            } else {
                log.error("关闭文档response-code: {}", response.getStatusLine().getStatusCode());
                throw new BusinessException("参数转码失败：" + response.getStatusLine().getStatusCode());
            }
        } catch (Exception e) {
            log.error("判断文档文件是否被打开出错Exception：{}", e.getMessage());
            throw new BusinessException("参数转码失败：" + e.getMessage());
        }

        return "";
    }


    /**
     * 将WebOffice服务器的文件，转为Pdf，生成pdf文件地址并下载
     *
     * @param wjjl    文件id
     * @param saveUrl WebOffice服务器保存的文件路径
     * @return
     */
    public Result getDocxToPdfFile(OaWjjl wjjl, String saveUrl) {
        boolean existFile = isExistFile(saveUrl);
        if (!existFile){
            log.error("需要下载的文档不存在");
            Result result = this.uploadWebOfficeFile(wjjl,wjjl.getFwjccmc(), wjjl.getFjdcflj());
            if (!result.isSuccess()){
                return Result.error(result.getMessage());
            }
        }

        String resultMsg = "";
        // 创建HttpGet对象
        StringBuffer urlString = new StringBuffer(webOfficeConstant.Dcs_Docx_To_Pdf_Api);

        /*urlString.append("?").append("convertType").append("=").append(3);
        urlString.append("&").append("fileUrl");
        urlString.append("=").append(WebOfficeFIle.WebOffice_download_Api);
        urlString.append("?").append("filePath").append("=").append(saveUrl);
        urlString.append("&").append("isDeleteFile").append("=").append(false);*/

        StringBuffer fileUrl = new StringBuffer(webOfficeConstant.WebOffice_download_Api);
        fileUrl.append("?").append("filePath").append("=").append(saveUrl);
        fileUrl.append("&").append("isDeleteFile").append("=").append("false");
//        System.out.println(fileUrl);

        NameValuePair pair1 = new BasicNameValuePair("convertType", "3");
        NameValuePair pair2 = new BasicNameValuePair("fileUrl",fileUrl.toString());
        List<NameValuePair> pairList = new ArrayList<>();
        pairList.add(pair1);
        pairList.add(pair2);

//        JSONObject jsonParams = new JSONObject();
//        jsonParams.put("convertType", 3);
//        jsonParams.put("fileUrl",fileUrl.toString());

//        System.out.println(urlString.toString());
        HttpPost httpRequest = new HttpPost(urlString.toString());
       /* if (httpRequest.getFirstHeader("Set-Cookie") != null) {
            System.out.println("cookie");
            String cookie = httpRequest.getFirstHeader("Set-Cookie").getValue();
            System.out.println(cookie);
            httpRequest.addHeader("Cookie", cookie);
        }*/
        httpRequest.addHeader("Cookie", "849899999d514676a3=2849534d163fd9d6a7384fb2986215a1; C9nvPf17Htt4O=5l12hjxiRPhAvnxIsYMnIYdq.u2KV270FrcHkhxdCKSSITC1zviGMk0MKcVEr5Ip_wnuiqnsliEP5jLH2FNg3La");
//        httpRequest.addHeader("Cookie", "C9nvPf17Htt4O=5Vf6oeh8oVwsO_6lr8.S_Lvqi6igknBbBerTmlyTkeRRfjugtqEK6vRQOqAYQ56bVp_lD4T03.CVBfO.6MC.iLa; Path=/; expires=Sun, 05 Jun 2033 09:16:30 GMT; Secure; HttpOnly");
//        httpRequest.addHeader("Content-Length","0");
//        httpRequest.addHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36");
//        httpRequest.addHeader("Accept", "*/*");
//        httpRequest.addHeader("Accept-Encoding", "gzip, deflate, br");
//        httpRequest.addHeader("Connection", "keep-alive");
        httpRequest.addHeader("Content-Type", "application/x-www-form-urlencoded");
//        RequestConfig defaultConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();//这个是重点，修改cookie格式
//        httpRequest.setConfig(defaultConfig);//这个是重点，将cookie配置方式放入请求中


//        httpRequest.setEntity(new StringEntity(jsonParams.toString(),"UTF-8"));
        // json参数
        try {
            httpRequest.setEntity(new UrlEncodedFormEntity(pairList,"UTF-8"));

            /*MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
            multipartEntityBuilder.setMode(HttpMultipartMode.RFC6532);   // 处理中文文件名称乱码
            multipartEntityBuilder.setCharset(Charset.forName("UTF-8"));
            multipartEntityBuilder.addTextBody("convertType", "3");
            multipartEntityBuilder.addTextBody("fileUrl", fileUrl.toString());
            HttpEntity httpEntity = multipartEntityBuilder.build();
            httpRequest.setEntity(httpEntity);*/

//            HttpClientParams.setCookiePolicy(HttpClients.createDefault().getParams(), CookiePolicy.BROWSER_COMPATIBILITY);
            HttpResponse response = HttpClients.createDefault().execute(httpRequest);
            log.info("response-statusCode: {}", response.getStatusLine().getStatusCode());

            /*String locationUrl = response.getFirstHeader("location").getValue();
            log.info("HttpClient locationUrl  => "+locationUrl);
            log.info("4--HttpClient StatusCode  => "+response.getStatusLine().getStatusCode());*/

            if (response.getStatusLine().getStatusCode() == 302) {
                /*Header header = response.getFirstHeader("location"); // 跳转的目标地址是在 HTTP-HEAD上
                String newuri = header.getValue(); // 这就是跳转后的地址，再向这个地址发出新申请
                log.info("newuri: {}", newuri);

                httpRequest = new HttpPost("https://bg.yjj.gxzf.gov.cn"+newuri);
                httpRequest.addHeader("Cookie", "849899999d514676a3=2849534d163fd9d6a7384fb2986215a1; C9nvPf17Htt4O=5l12hjxiRPhAvnxIsYMnIYdq.u2KV270FrcHkhxdCKSSITC1zviGMk0MKcVEr5Ip_wnuiqnsliEP5jLH2FNg3La");
                httpRequest.setHeader("Content-Type", "application/x-www-form-urlencoded");

                response = HttpClients.createDefault().execute(httpRequest);
                int code = response.getStatusLine().getStatusCode();
                locationUrl = response.getLastHeader("location").getValue();
                log.info("5--HttpClient new Code  => "+code);
                log.info("6--HttpClient locationUrl  => "+locationUrl);*/
            }


            if (response.getStatusLine().getStatusCode() == 200){

                HttpEntity res = response.getEntity();
                if (res != null) {
                    String s = EntityUtils.toString(res, "UTF-8");
                    JSONObject jsonObject2 = JSONObject.parseObject(s);
                    log.info("WebOffice将Docx转换为Pdf,返回值: {}",jsonObject2);

                    String errorcode = jsonObject2.getString("errorcode");
                    if (Integer.valueOf(errorcode) == 0){
                        JSONObject data = jsonObject2.getJSONObject("data");
                        String viewUrl = data.getString("viewUrl"); // pdf文件路径
                        log.info("viewUrl: {}",viewUrl);

                        if (StringUtils.isBlank(viewUrl)) {
                            return Result.error("下载pdf文件路径viewUrl参数为空");
                        }

                        this.getDownloadPdfFile2(wjjl, viewUrl); // 下载pdf文件

                        log.info("WebOffice将word转pdf的errorcode: {}",errorcode);
                    }else {
                        resultMsg = jsonObject2.getString("message");
                        log.error("WebOffice将word转pdf的message: {}",resultMsg);
                        return Result.error("WebOffice将word转pdf的message: "+resultMsg);
                    }
                }
            }
        }catch (Exception e){
            log.error("WebOffice将word转pdf的Exception: {}",e.getMessage());
            return Result.error("WebOffice将word转pdf的Exception: "+e.getMessage());
        }

        return Result.ok("转换成功");
    }

    /**
     * 将WebOffice服务器word文档转为Pdf的文件下载
     * @param wjjl 当前文件对象
     * @param viewUrl pdf文件下载https路径
     */
    public void getDownloadPdfFile2(OaWjjl wjjl,String viewUrl){
       /* StrBuilder url = new StrBuilder(WebOfficeFIle.WebOffice_download_Api);
        url.append("?").append("filePath").append(saveUrl);
        url.append("&").append("isDeleteFile").append(isDel);*/

        String pdfname = GetUuIdUtils.generateUuid() + ".pdf"; // 文件名称

        try{
            HttpGet httpget = new HttpGet(viewUrl);
            httpget.addHeader("Cookie", "849899999d514676a3=2849534d163fd9d6a7384fb2986215a1; C9nvPf17Htt4O=5l12hjxiRPhAvnxIsYMnIYdq.u2KV270FrcHkhxdCKSSITC1zviGMk0MKcVEr5Ip_wnuiqnsliEP5jLH2FNg3La");
            // 加入Referer,防止防盗链
            httpget.setHeader("Referer",viewUrl);
            SSLConnectionSocketFactory sslsf=new SSLConnectionSocketFactory(
                    SSLContexts.custom().loadTrustMaterial(null,new TrustSelfSignedStrategy()).build(),
                    NoopHostnameVerifier.INSTANCE);
            // 创建Httpclient对象
            CloseableHttpClient httpClient=HttpClients.custom().setSSLSocketFactory(sslsf).build();

            HttpResponse response=httpClient.execute(httpget);
            HttpEntity entity=response.getEntity();
            InputStream is=entity.getContent();

            String nowDay = DateUtil.today(); // 获取当前日期 yyyy-MM-dd
            String newDir = "/"+nowDay;

            String realurl = oaBusinessConstant.YUNCEHNG_PATH_UPLOAD + newDir;
            File newDirUrl = new File(realurl);
            if (!newDirUrl.exists()){
                newDirUrl.mkdirs();
            }

            FileOutputStream fileout = new FileOutputStream(realurl + "/" + pdfname);
            byte[]buffer = new byte[1024*10];
            int ch = 0;
            while((ch = is.read(buffer)) != -1){
                fileout.write(buffer,0,ch);
            }
            is.close();
            fileout.flush();
            fileout.close();

            String fcflj = wjjl.getFjdcflj(); // 旧的文档路径
            if (StringUtils.isNotBlank(wjjl.getFjdcflj())){
                oaLocalFileUploadUtils.deleteLocalFileUrl(wjjl.getFjdcflj());
            }
            wjjl.setFwjccmc(newDir + "/" + pdfname); // pdf路径
            wjjl.setFjdcflj(fcflj);
            wjjl.setFwjlx(".pdf");
            wjjl.setFwjccmc(pdfname);
//            localFileUploadUtils.updateById(wjjl);

        }catch(Exception e){
            log.error("将WebOffice服务器word文档转为Pdf的文件下载Exception出错：{}", e.getMessage());
        }
    }

    /**
     * 将WebOffice服务器中的word文件关闭保存并下载
     * @param wjjl
     * @param saveUrl
     * @param isDel
     */
    public void getWebOfficeDownloadFile2(OaWjjl wjjl, String saveUrl, boolean isDel){
        boolean existFile = isExistFile(saveUrl);
        if (!existFile){
            log.error("需要下载的文档不存在");
            return;
            /*Result result = this.uploadWebOfficeFile(wjjl, wjjl.getFwjccmc(), wjjl.getFcflj());
            if (!result.isSuccess()){
                log.error("将WebOffice服务器中的word文件下载的文档不存在，上传文档失败：{}",result.getMessage());
                return;
            }*/
        }

        StringBuffer url = new StringBuffer(webOfficeConstant.WebOffice_download_Api);
        url.append("?").append("filePath").append("=").append(saveUrl);
        url.append("&").append("isDeleteFile").append("=").append(isDel);

        String pdfname = GetUuIdUtils.generateUuid() + Util.getWjHz(saveUrl); // 文件名称

        try{
            HttpGet httpget = new HttpGet(url.toString());
            // 加入Referer,防止防盗链
            httpget.setHeader("Referer",url.toString());
            SSLConnectionSocketFactory sslsf=new SSLConnectionSocketFactory(
                    SSLContexts.custom().loadTrustMaterial(null,new TrustSelfSignedStrategy()).build(),
                    NoopHostnameVerifier.INSTANCE);
            // 创建Httpclient对象
            CloseableHttpClient httpClient=HttpClients.custom().setSSLSocketFactory(sslsf).build();

            HttpResponse response=httpClient.execute(httpget);

            HttpEntity entity = response.getEntity();
            InputStream is = entity.getContent();

            String nowDay = DateUtil.today(); // 获取当前日期 yyyy-MM-dd
            String newDir = "/" + nowDay;

            String realurl = oaBusinessConstant.YUNCEHNG_PATH_UPLOAD + newDir;
            File newDirUrl = new File(realurl);
            if (!newDirUrl.exists()) {
                newDirUrl.mkdirs();
            }

            FileOutputStream fileout = new FileOutputStream(realurl + "/" + pdfname);
            byte[] buffer = new byte[1024 * 10];
            int ch = 0;
            while ((ch = is.read(buffer)) != -1) {
                fileout.write(buffer, 0, ch);
            }
            is.close();
            fileout.flush();
            fileout.close();

            String fcflj = wjjl.getFcfljxn(); // 旧的文件
            wjjl.setFwjccmc(newDir + "/" + pdfname);
            if (StringUtils.isNotBlank(wjjl.getFjdcflj())){
                oaLocalFileUploadUtils.deleteLocalFileUrl(wjjl.getFjdcflj());
            }
            wjjl.setFjdcflj(fcflj);
            wjjl.setFwjccmc(pdfname);
            boolean isFlag = oaWjjlService.updateById(wjjl);
            if (isFlag){
                this.deleteFile(fcflj);
                /*Result result = this.uploadWebOfficeFile(wjjl, wjjl.getFwjccmc(), wjjl.getFcflj());
                if (!result.isSuccess()){
                    log.error("将WebOffice服务器中的word文件下载的文档不存在，上传文档失败：{}",result.getMessage());
                }*/
            }

        }catch(Exception e){
            log.error("将WebOffice服务器中的word文件下载Exception出错：{}", e.getMessage());
        }
    }

    /**
     * 将WebOffice服务器中的word文件关闭保存并下载   服务端 正文
     *
     * @param wjjl
     * @param saveUrl
     * @param isDel
     */
    public void getWebOfficeDownloadFile2ByOazw(OaWjjl wjjl, String saveUrl, boolean isDel) {
        saveUrl = CharacterEncodingConvertUtils.chineseToUnicode(saveUrl);
        boolean existFile = isExistFile(saveUrl);
        if (!existFile) {
            log.error("需要下载的文档不存在");
            return;
            /*Result result = this.uploadWebOfficeFile(wjjl, wjjl.getFwjccmc(), wjjl.getFcflj());
            if (!result.isSuccess()){
                log.error("将WebOffice服务器中的word文件下载的文档不存在，上传文档失败：{}",result.getMessage());
                return;
            }*/
        }

        StringBuffer url = new StringBuffer(webOfficeConstant.WebOffice_download_Api);
        url.append("?").append("filePath").append("=").append(saveUrl);
        url.append("&").append("isDeleteFile").append("=").append(isDel);

        String pdfname = GetUuIdUtils.generateUuid() + Util.getWjHz(saveUrl); // 文件名称

        try {
            HttpGet httpget = new HttpGet(url.toString());
            // 加入Referer,防止防盗链
            httpget.setHeader("Referer", url.toString());
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                    SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(),
                    NoopHostnameVerifier.INSTANCE);
            // 创建Httpclient对象
            CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();

            HttpResponse response = httpClient.execute(httpget);

            HttpEntity entity = response.getEntity();
            InputStream is = entity.getContent();

            String nowDay = DateUtil.today(); // 获取当前日期 yyyy-MM-dd
            String newDir = "/" + OaCommonFlowConstant.OA_ZW + "/" + nowDay;

            String realurl = oaBusinessConstant.UPLOAD_OA_ZW + newDir;
            File newDirUrl = new File(realurl);
            if (!newDirUrl.exists()) {
                newDirUrl.mkdirs();
            }

            FileOutputStream fileout = new FileOutputStream(realurl + "/" + pdfname);
            byte[] buffer = new byte[1024 * 10];
            int ch = 0;
            while ((ch = is.read(buffer)) != -1) {
                fileout.write(buffer, 0, ch);
            }
            is.close();
            fileout.flush();
            fileout.close();

            String fcflj = wjjl.getFjdcflj(); // 旧的文件
            wjjl.setFjdcflj(newDir + "/" + pdfname);
            if (StringUtils.isNotBlank(wjjl.getFjdcflj())) {
                oaLocalFileUploadUtils.deleteLocalFileUrlByZdy(wjjl.getFjdcflj());
            }
            wjjl.setFjdcflj(fcflj);
            boolean isFlag = oaWjjlService.updateById(wjjl);
            if (isFlag) {
                this.deleteFile(fcflj);
                /*Result result = this.uploadWebOfficeFile(wjjl, wjjl.getFwjccmc(), wjjl.getFcflj());
                if (!result.isSuccess()){
                    log.error("将WebOffice服务器中的word文件下载的文档不存在，上传文档失败：{}",result.getMessage());
                }*/
            }

        } catch (Exception e) {
            log.error("将WebOffice服务器中的word文件下载Exception出错：{}", e.getMessage());
        }
    }

    /**
     * 将WebOffice服务器中的word文件关闭保存并下载  （文件模板库）
     * @param wjjl
     * @param saveUrl
     * @param isDel
     */
//    public void getWebOfficeDownloadFile2ByWjmb(OaWjjl wjjl, String saveUrl, boolean isDel){
//        saveUrl = CharacterEncodingConvertUtils.chineseToUnicode(saveUrl);
//        boolean existFile = isExistFile(saveUrl);
//        if (!existFile){
//            log.error("需要下载的文档不存在");
//            return;
//            /*Result result = this.uploadWebOfficeFile(wjjl, wjjl.getFwjccmc(), wjjl.getFcflj());
//            if (!result.isSuccess()){
//                log.error("将WebOffice服务器中的word文件下载的文档不存在，上传文档失败：{}",result.getMessage());
//                return;
//            }*/
//        }
//
//        StringBuffer url = new StringBuffer(WebOfficeConstant.WebOffice_download_Api);
//        url.append("?").append("filePath").append("=").append(saveUrl);
//        url.append("&").append("isDeleteFile").append("=").append(isDel);
//
//        try{
//            HttpGet httpget = new HttpGet(url.toString());
//            // 加入Referer,防止防盗链
//            httpget.setHeader("Referer",url.toString());
//            SSLConnectionSocketFactory sslsf=new SSLConnectionSocketFactory(
//                    SSLContexts.custom().loadTrustMaterial(null,new TrustSelfSignedStrategy()).build(),
//                    NoopHostnameVerifier.INSTANCE);
//            // 创建Httpclient对象
//            CloseableHttpClient httpClient=HttpClients.custom().setSSLSocketFactory(sslsf).build();
//
//            HttpResponse response=httpClient.execute(httpget);
//
//            HttpEntity entity = response.getEntity();
//            InputStream is = entity.getContent();
//
//            String sjmc = "";
//            if (StringUtils.isNotBlank(wjjl.getFmbbt())){
//                sjmc = wjjl.getFmbbt() + GetUuIdUtils.generateUuid();
//            }
//            String pdfname = sjmc+ Util.getWjHz(saveUrl); // 文件名称
//            String nowDay = DateUtil.today(); // 获取当前日期 yyyy-MM-dd
//            String newDir = "";
//            if (StringUtils.isNotBlank(wjjl.getFywflcode())){
//                newDir = "/" + wjjl.getFywflcode();
//            }else {
//                newDir = "/" + nowDay;
//            }
//
//            String realurl = businessConstant.UPLOAD_WJMB_PATH + newDir;
//            File newDirUrl = new File(realurl);
//            if (!newDirUrl.exists()) {
//                newDirUrl.mkdirs();
//            }
//
//            FileOutputStream fileout = new FileOutputStream(realurl + "/" + pdfname);
//            byte[] buffer = new byte[1024 * 10];
//            int ch = 0;
//            while ((ch = is.read(buffer)) != -1) {
//                fileout.write(buffer, 0, ch);
//            }
//            is.close();
//            fileout.flush();
//            fileout.close();
//
//            String fcflj = wjjl.getFcflj(); // 旧的文件
//            wjjl.setFcflj(newDir + "/" + pdfname);
//
//            if (StringUtils.isNotBlank(fcflj)){
//                localFileUploadUtils.deleteLocalWjmbFileUrl(fcflj);
//            }
//            wjjl.setFwjccmc(pdfname);
//            boolean isFlag = spcyRsWjmbService.updateById(wjjl);
//            if (isFlag){
//                this.deleteFile(fcflj);
//                /*Result result = this.uploadWebOfficeFile(wjjl, wjjl.getFwjccmc(), wjjl.getFcflj());
//                if (!result.isSuccess()){
//                    log.error("将WebOffice服务器中的word文件下载的文档不存在，上传文档失败：{}",result.getMessage());
//                }*/
//            }
//
//        }catch(Exception e){
//            log.error("将WebOffice服务器中的word文件下载Exception出错：{}", e.getMessage());
//        }
//    }

    /**
     * 删除文档
     */
    public void deleteFile(String saveUrl){
        boolean existFile = isExistFile(saveUrl);
        if (!existFile){
            log.error("需要下载的文档不存在");
            return;
        }

        StringBuffer url = new StringBuffer(webOfficeConstant.WebOffice_download_Api);
        url.append("?").append("filePath").append("=").append(saveUrl);
        url.append("&").append("isDeleteFile").append("=").append(true);

        String pdfname = GetUuIdUtils.generateUuid() + Util.getWjHz(saveUrl); // 文件名称

        try{
            HttpGet httpget = new HttpGet(url.toString());
            // 加入Referer,防止防盗链
            httpget.setHeader("Referer",url.toString());
            SSLConnectionSocketFactory sslsf=new SSLConnectionSocketFactory(
                    SSLContexts.custom().loadTrustMaterial(null,new TrustSelfSignedStrategy()).build(),
                    NoopHostnameVerifier.INSTANCE);
            // 创建Httpclient对象
            CloseableHttpClient httpClient=HttpClients.custom().setSSLSocketFactory(sslsf).build();

            HttpResponse response=httpClient.execute(httpget);

            HttpEntity entity = response.getEntity();
            InputStream is = entity.getContent();

            String nowDay = DateUtil.today(); // 获取当前日期 yyyy-MM-dd
            String newDir = "/" + nowDay;

            String realurl = oaBusinessConstant.YUNCEHNG_PATH_UPLOAD + newDir;
            File newDirUrl = new File(realurl);
            if (!newDirUrl.exists()) {
                newDirUrl.mkdirs();
            }

            FileOutputStream fileout = new FileOutputStream(realurl + "/" + pdfname);
            byte[] buffer = new byte[1024 * 10];
            int ch = 0;
            while ((ch = is.read(buffer)) != -1) {
                fileout.write(buffer, 0, ch);
            }
            is.close();
            fileout.flush();
            fileout.close();

            File delFile = new File(realurl + "/" + pdfname);
            if (delFile.exists()){
                delFile.delete();
            }

        }catch(Exception e){
            log.error("删除文档Exception出错：{}", e.getMessage());
        }
    }


    /**
     * 打开文档
     */
    public String openFile(OaWjjl wjjl,String fileId,String saveUrl){
        String params = "";
        params += "{";
        params += "\"method\": "+1+",";
        params += "\"params\":";
        params += "{";
        params += "\"userRight\": "+0+",";
        params += "\"userId\": \""+ WebOfficeConstant.WebOffice_User_Id+"\",";
        params += "\"fileId\": \""+fileId+"\",";
        params += "\"filePath\": \""+saveUrl+"\"";
        params += "}";
        params += "}";
        JSONObject jsonParams = JSON.parseObject(params);

        // 转码参数 utf-8
        String paramsDecode = "";
        paramsDecode = StringPatternUtils.encode(jsonParams.toString());

        StringBuffer reqHttpUrl = new StringBuffer(webOfficeConstant.WebOffice_Api);
        reqHttpUrl.append("?");
        reqHttpUrl.append("jsonParams").append("=").append(paramsDecode);
        HttpPost httpRequest = initHttpPost(reqHttpUrl.toString());
//        httpRequest.setEntity(new StringEntity(jsonParams.toString(),"UTF-8"));
        try {
            HttpResponse response = HttpClients.createDefault().execute(httpRequest);

            if (response.getStatusLine().getStatusCode() == 200){
                HttpEntity res = response.getEntity();
                if (res != null) {
                    String s = EntityUtils.toString(res, "UTF-8");

                    JSONObject jsonObject2 = JSONObject.parseObject(s);

                    String errorCode = jsonObject2.getString("errorCode");
                    log.info("打开文档-errorCode: {}",errorCode);

                    String errorMessage = jsonObject2.getString("errorMessage");
                    if (errorCode.equals("0")){
                        log.info("打开文档-errorMessage: {}",errorMessage);
                        JSONObject result = jsonObject2.getJSONObject("result");
                        String urls = result.getString("urls");
                        return urls;
                    } else if (errorCode.equals("400001")){
                        if (errorMessage.equals("文档不存在。")){
                            Result result = this.uploadWebOfficeFile(wjjl, wjjl.getFwjccmc(), wjjl.getFcfljxn());
                            if (!result.isSuccess()){
                                log.error("将WebOffice服务器中的word文件下载的文档不存在，上传文档失败：{}",result.getMessage());
                                throw new BusinessException("将WebOffice服务器中的word文件下载的文档不存在，上传文档失败：{}"+result.getMessage());
                            }else {
                                String url2 = this.openFile(wjjl, fileId, saveUrl);
                                return url2;
                            }
                        } else {
                            log.error("打开文档-errorMessage: {}", errorMessage);
                            throw new BusinessException("打开文档-errorMessage: {}" + errorMessage);
                        }
                    }

                }
            }else {
                log.error("关闭文档response-code: {}", response.getStatusLine().getStatusCode());
                throw new BusinessException("参数转码失败："+ response.getStatusLine().getStatusCode());
            }
        }catch (Exception e){
            log.error("判断文档文件是否被打开出错Exception：{}",e.getMessage());
            throw new BusinessException("参数转码失败："+e.getMessage());
        }

        return "";
    }

    /**
     * 判断文档是否存在
     */
    public boolean isExistFile(String saveUrl){
        StringBuffer url = new StringBuffer(webOfficeConstant.WebOffice_download_Api);
        url.append("?").append("filePath").append("=").append(saveUrl);
        url.append("&").append("isDeleteFile").append("=").append(false);

        try{
            HttpGet httpget = new HttpGet(url.toString());
            // 加入Referer,防止防盗链
            httpget.setHeader("Referer",url.toString());
            SSLConnectionSocketFactory sslsf=new SSLConnectionSocketFactory(
                    SSLContexts.custom().loadTrustMaterial(null,new TrustSelfSignedStrategy()).build(),
                    NoopHostnameVerifier.INSTANCE);
            // 创建Httpclient对象
            CloseableHttpClient httpClient=HttpClients.custom().setSSLSocketFactory(sslsf).build();

            HttpResponse response = httpClient.execute(httpget);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity res = response.getEntity();
                if (res != null) {
                    /*long contentLength = res.getContentLength();
                    if (contentLength > 58){
                        return true;
                    }*/
                    String s = EntityUtils.toString(res, "UTF-8");
                    boolean result = false;
                    try {
                        Object obj = JSON.parse(s);
                        result = true;
                    } catch (Exception e) {
                        result = false;
                    }
                    if (!result){
                        return true;
                    }

                    JSONObject jsonObject2 = JSONObject.parseObject(s);
                    String errorCode = jsonObject2.getString("errorCode");
                    log.info("判断文档是否存在-errorCode: {}",errorCode);

                    String errorMessage = jsonObject2.getString("errorMessage");
                    log.info("判断文档是否存在-errorMessage: {}",errorMessage);
                    if (errorCode.equals("0")){
                        return true;
                    } else {
                        log.error("判断文档是否存在-errorMessage: {}",errorMessage);
                        return false;
                    }

                }
            }else {
                log.error("判断文档是否存在response-code: {}", response.getStatusLine().getStatusCode());
                throw new BusinessException("判断文档是否存在response-code: "+response.getStatusLine().getStatusCode());
            }

        }catch(Exception e){
            log.error("判断文档是否存在出错Exception：{}", e.getMessage());
            throw new BusinessException("判断文档是否存在出错Exception: "+e.getMessage());
        }

        return false;
    }

    /**
     * 关闭文档
     */
    public Result closeFile(String fileId){
        String params = "";
        params += "{";
        params += "\"method\": "+3+",";
        params += "\"params\":";
        params += "{";
        params += "\"fileId\": \""+fileId+"\"";
        params += "}";
        params += "}";
       /* params.append("{");
        params.append("\"").append("method").append("\"").append(":").append(3).append(",");
        params.append("\"").append("params").append("\"").append(":");
        params.append("{");
        params.append("\"").append("fileId").append("\"").append(":").append(fileId);
        params.append("}");
        params.append("}");*/
        JSONObject jsonParams = JSON.parseObject(params.toString());

        // 转码参数 utf-8
        String paramsDecode = "";
        paramsDecode = StringPatternUtils.encode(jsonParams.toString());

        StringBuffer reqHttpUrl = new StringBuffer(webOfficeConstant.WebOffice_Api);
        reqHttpUrl.append("?");
        reqHttpUrl.append("jsonParams").append("=").append(paramsDecode);

        HttpPost httpRequest = initHttpPost(reqHttpUrl.toString());
//        httpRequest.setEntity(new StringEntity(jsonParams.toString(),"UTF-8"));
        try {
            HttpResponse response = HttpClients.createDefault().execute(httpRequest);

            if (response.getStatusLine().getStatusCode() == 200){
                HttpEntity res = response.getEntity();
                if (res != null) {
                    String s = EntityUtils.toString(res, "UTF-8");

                    JSONObject jsonObject2 = JSONObject.parseObject(s);

                    String errorCode = jsonObject2.getString("errorCode");
                    log.info("关闭文档-errorCode: {}",errorCode);

                    String errorMessage = jsonObject2.getString("errorMessage");
                    if (errorCode.equals("0")){
                        log.info("关闭文档-errorMessage: {}",errorMessage);
                        return Result.ok("关闭文档成功");
                    }else {
                        log.error("关闭文档-errorMessage: {}",errorMessage);
                        return Result.error("关闭文档-errorMessage: "+errorMessage);
                    }

                }
            }else {
                if (response.getStatusLine().getStatusCode() == 313){
                    log.error("文档已经关闭response-code: {}", response.getStatusLine().getStatusCode());
                    return Result.ok("文档已经关闭response-code: " + response.getStatusLine().getStatusCode());
                }else {
                    log.error("关闭文档response-code: {}", response.getStatusLine().getStatusCode());
                    return Result.error("关闭文档response-code: " + response.getStatusLine().getStatusCode());
                }
            }
        }catch (Exception e){
            log.error("关闭文档出错Exception：{}",e.getMessage());
            return Result.error("关闭文档出错Exception: "+e.getMessage());
        }

        return Result.ok("关闭文档成功");
    }

    /**
     * 判断文档文件是否被打开 (false[未打开]；true[已打开])
     */
    public boolean isOpenFile(String fileId){
        String params = "";
        params += "{";
        params += "\"method\": "+4+",";
        params += "\"params\":";
        params += "{";
        params += "\"fileId\": \""+fileId+"\"";
        params += "}";
        params += "}";
      /*  params.append("\"").append("params").append("\"").append(":");
        params.append("{");
        params.append("\"").append("fileId").append("\"").append(":").append(fileId);
        params.append("}");
        params.append("}");*/
        JSONObject jsonParams = JSON.parseObject(params);

        // 转码参数 utf-8
        String paramsDecode = "";
        paramsDecode = StringPatternUtils.encode(jsonParams.toString());

        StringBuffer reqHttpUrl = new StringBuffer(webOfficeConstant.WebOffice_Api);
        reqHttpUrl.append("?");
        reqHttpUrl.append("jsonParams").append("=").append(paramsDecode);
        HttpPost httpRequest = initHttpPost(reqHttpUrl.toString());
//        httpRequest.setEntity(new StringEntity(jsonParams.toString(),"UTF-8"));
        try {
            HttpResponse response = HttpClients.createDefault().execute(httpRequest);

            if (response.getStatusLine().getStatusCode() == 200){
                HttpEntity res = response.getEntity();
                if (res != null) {
                    String s = EntityUtils.toString(res, "UTF-8");

                    JSONObject jsonObject2 = JSONObject.parseObject(s);
//                    log.info("判断文档文件是否被打开-返回值: {}",jsonObject2);

                    String errorCode = jsonObject2.getString("errorCode");
                    log.info("判断文档文件是否被打开-errorCode: {}",errorCode);

                    String errorMessage = jsonObject2.getString("errorMessage");

                    // result (判断是否已经打开：false[未打开]；true[已打开])
                    boolean result = Boolean.parseBoolean(jsonObject2.getString("result"));
                    log.info("判断文档文件是否被打开-result: {}",result);
                    if (errorCode.equals("0")){
                        log.info("判断文档文件是否被打开-errorMessage: {}",errorMessage);
                        return result;
                    }else {
                        log.error("判断文档文件是否被打开-errorMessage: {}",errorMessage);
                        throw new BusinessException("判断文档文件是否被打开-errorMessage: {}"+errorMessage);
                    }

                }
            }else {
                log.error("关闭文档response-code: {}", response.getStatusLine().getStatusCode());
                throw new BusinessException("参数转码失败："+ response.getStatusLine().getStatusCode());
            }
        }catch (Exception e){
            log.error("判断文档文件是否被打开出错Exception：{}",e.getMessage());
            throw new BusinessException("参数转码失败："+e.getMessage());
        }

        return true;
    }

    /**
     *
     */
    public boolean againEditPdfOnlineFile(OaWjjl wjjl){
        if (StringUtils.isBlank(wjjl.getFjdcflj())){
            return true;
        }
        if (StringUtils.isBlank(wjjl.getFcfljxn())){
            return true;
        }
        if (StringUtils.isBlank(wjjl.getFwjlx()) || !wjjl.getFwjlx().equals(".pdf")){
            return true;
        }
        Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(wjjl);

        String fjdcflj = wjjl.getFjdcflj(); // 旧的文件路径
        String oldWjlx = Util.getWjHz(fjdcflj); // 旧的文件类型
        oaLocalFileUploadUtils.deleteLocalFileUrl(wjjl.getFcfljxn()); // 删除文件

        wjjl.setFwjlx(oldWjlx);
        wjjl.setFcfljxn(fjdcflj);
        wjjl.setFwjccmc(Util.getWjmc(fjdcflj));
        wjjl.setFjdcflj("");
//        wjjl.setFgzzt(SpcyConstant.WJJL_ZT_GZ_NO);
//        wjjl.setFdxzt(SpcyConstant.WJJL_ZT_DX_NO);
//        wjjl.setFyxzt(SpcyConstant.WJJL_ZT_YX_NO);
        boolean isFlag = oaWjjlService.updateById(wjjl);
        if (isFlag) {
            String logNr = "重新编辑PDF文件" + wjjl.getFwjlx1() + "：文件名【" + wjjl.getFwjccmc() + "】;";
            logNr += LogUtils.BeanModifyMsg(wjjl, oldMap);
//            spcyLogService.addLogs("在线编辑", logNr, wjjl.getFpid(), LogConstant.LOGS_SQSX_WJJL, SpcyConstant.LOGS_SYS_TYPE_XG);
        }

        return isFlag;
    }

    /**
     * 初始化HttpPost请求头
     * @param url 请求地址
     * @return
     */
    private HttpPost initHttpPost(String url){
        HttpPost httpRequest = new HttpPost(url);
        // 设置请求头，在Post请求中限制了浏览器后才能访问
        httpRequest.addHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36");
        httpRequest.addHeader("Accept", "*/*");
        httpRequest.addHeader("Accept-Encoding", "gzip, deflate, br");
        httpRequest.addHeader("Content-Type", "application/json");
        httpRequest.addHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8");
        httpRequest.addHeader("Connection", "keep-alive");
        return httpRequest;
    }
}
